from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import UserProfile, BetRecord
from django.db.models import Sum, Q
from django.utils import timezone
from datetime import timedelta, datetime


class ProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = '用户资料'
    fk_name = 'user'


class InviterFilter(admin.SimpleListFilter):
    title = '邀请人'
    parameter_name = 'inviter'

    def lookups(self, request, model_admin):
        # 修正点1：通过UserProfile查询邀请人关系
        return UserProfile.objects.filter(
            invitees__isnull=False  # 使用UserProfile的反向关联
        ).distinct().values_list(
            'user__id', 'user__username'  # 获取对应的User字段
        )

    def queryset(self, request, queryset):
        if self.value():
            # 修正点2：调整过滤路径
            return queryset.filter(
                profile__inviter__user__id=self.value()  # user → profile → inviter → user
            )
        return queryset


class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline,)
    exclude = ('profile',)
    list_display = (
        'username', 'email', 'date_joined',
        'last_login', 'get_score', 'get_inviter',
        'get_daily_flow', 'get_weekly_flow', 'get_total_flow'
    )
    list_filter = (InviterFilter, 'is_staff', 'is_active')

    def get_score(self, obj):
        return obj.profile.score
    get_score.short_description = '积分'

    def get_inviter(self, obj):
        # 确保安全访问嵌套关系
        if obj.profile.inviter and obj.profile.inviter.user:
            return obj.profile.inviter.user.username
        return '无'
    get_inviter.short_description = '邀请人'

    def get_daily_flow(self, obj):
        today = timezone.now().replace(hour=0, minute=0, second=0)
        return BetRecord.objects.filter(
            user=obj,
            created_at__gte=today,
            is_cancelled=False,
        ).aggregate(Sum('amount'))['amount__sum'] or 0
    get_daily_flow.short_description = '当日流水'

    def get_weekly_flow(self, obj):
        today = timezone.now().date()
        monday = today - timedelta(days=today.weekday())
        start = timezone.make_aware(datetime(monday.year, monday.month, monday.day))
        return BetRecord.objects.filter(
            user=obj,
            created_at__gte=start,
            is_cancelled=False
        ).aggregate(Sum('amount'))['amount__sum'] or 0
    get_weekly_flow.short_description = '周流水'

    def get_total_flow(self, obj):
        return BetRecord.objects.filter(
            user=obj,
            is_cancelled=False
        ).aggregate(Sum('amount'))['amount__sum'] or 0
    get_total_flow.short_description = '总流水'


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)